#include <gtest/gtest.h>
#include "../sdk/ServiceManager.h"
#include "../sdk/LoadBalance.h"
#include "../sdk/Service.h"
#include "../sdk/RoundRobinStrategy.hpp"

// 测试 ServiceManager 的基本功能
class ServiceManagerTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 初始化资源，如注册服务实例
        manager = &ServiceManager::getInstance();
        manager->setConsulConfig("http://127.0.0.1:8500", "");
    }

    void TearDown() override {
        // 清理资源（如果需要）
    }

    ServiceManager* manager;
};

// 测试服务注册与发现
TEST_F(ServiceManagerTest, RegisterAndFindService) {

    ServiceItem item("127.0.0.1", 8081, "TestService");
    manager->addServiceInstance("TestService", item, 20);
    manager->syncServices();
    const std::shared_ptr<RoundRobinStrategy> strategy = std::make_shared<RoundRobinStrategy>();
    manager->setLoadBalanceStrategy(strategy);
    auto service = manager->getNextService("TestService");
    std::cout << "Service: " << service.getName()<<" "<<service.getIp() << ":" << service.getPort() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(100));
    
    //ASSERT_TRUE(service);
    EXPECT_EQ(service.getIp(), "127.0.0.1");
    EXPECT_EQ(service.getPort(), 8081);
}

// 测试负载均衡策略（例如轮询）
TEST_F(ServiceManagerTest, LoadBalanceStrategyRoundRobin) {
    // 注册多个服务实例
    const std::shared_ptr<RoundRobinStrategy> strategy = std::make_shared<RoundRobinStrategy>();
    manager->setLoadBalanceStrategy(strategy);
    manager->addServiceInstance("TestService", ServiceItem("127.0.0.1", 8081, "TestService"), 20);
    manager->addServiceInstance("TestService", ServiceItem("127.0.0.2", 8082, "TestService"), 20);
    manager->addServiceInstance("TestService", ServiceItem("127.0.0.3", 8083, "TestService"), 20);

    for(int i = 0; i < 10; i++){
        auto service = manager->getNextService("TestService");
        std::cout << "Service: " << service.getName()<<" "<<service.getIp() << ":" << service.getPort() << std::endl;
    }
    manager->syncServices();
    std::this_thread::sleep_for(std::chrono::seconds(100));

}

// 测试服务移除功能
TEST_F(ServiceManagerTest, RemoveService) {
    ServiceItem item("127.0.0.1", 8080, "ToRemoveService");
    manager->addServiceInstance("ToRemoveService", item, 20);
    manager->removeServiceInstance("ToRemoveService", item);

    auto service = manager->getNextService("ToRemoveService");
    //EXPECT_EQ(service, nullptr); // 应该找不到服务
}